package com.hliushi.learn.jms.rocketmq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;

import java.util.concurrent.TimeUnit;

/**
 * @author llhuang10
 * @date 2021/7/22 17:04
 */
@Slf4j
public class SyncProducer {


    /**
     * 消息发送者步骤分析
     * 1.创建消息生产者producer, 并指定生产者组名
     * 2.指定Nameserver地址
     * 3.启动producer
     * 4.创建消息对象, 指定主题Topic, Tag和消息体
     * 5.发送消息
     * 6.关闭生产者producer
     *
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // 1.创建消息生产者producer，并制定生产者组名
        DefaultMQProducer producer = new DefaultMQProducer("group01");
        // 2.指定Nameserver地址
        producer.setNamesrvAddr("cvm-node01:9876;cvm-node02:9876");
        // producer.setNamesrvAddr("localhost:9876");
        // producer.setNamesrvAddr("cvm-node02:9876");
        // 3.启动producer
        producer.start();

        for (int i = 0; i < 10; i++) {
            // 4.创建消息对象, 指定主题Topic, Tag和消息体
            Message msg = new Message("springboot-mq", "Tag1", ("hello world" + i).getBytes());

            // Exception in thread "main" org.apache.rocketmq.client.exception.MQClientException: No route info of this topic, springboot-mq
            // 5.发送消息
            SendResult result = producer.send(msg);
            // 发送状态
            SendStatus status = result.getSendStatus();

            log.info("发送结果: {}, status: {}", result, status);

            // 线程睡一秒
            TimeUnit.SECONDS.sleep(1);
        }

        // 6.关闭生产者producer
        producer.shutdown();

    }

}
